package com.anjie.powerproject.aop;

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @author zxy
 * 切面，所有service方法调用之前，和调用之后打印调用参数
 */
@Aspect
@Component
@Profile(value = {"dev", "testing"})
public class MethodInvokeAspect {
    private static final Logger logger = LoggerFactory.getLogger(MethodInvokeAspect.class);

    @Pointcut("@within(org.springframework.stereotype.Service)")
    public void invokePointCut(){}

    @Before("invokePointCut()")
    public void beforeInvoke(JoinPoint joinPoint) {
        String className = joinPoint.getSignature().getDeclaringType().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        logger.info("[{}] {} params:{}", className, methodName, Arrays.deepToString(args));
    }

    @AfterReturning(value = "invokePointCut()", returning = "result")
    public void afterInvoke(JoinPoint joinPoint, Object result) {
        String className = joinPoint.getSignature().getDeclaringType().getName();
        String methodName = joinPoint.getSignature().getName();
        logger.info("[{}] {} return:{}", className, methodName, JSON.toJSONString(result));
    }
}
